package com.imooc.config;

import com.imooc.dao.UserRepository;
import com.imooc.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 用户服务
 *
 * @author 顾志杰
 * @date 2020/10/13-9:15
 */
@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        String password = passwordEncoder().encode("111");
//        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ACTIVITI_USER"));

        /*读取数据库判断用户*/
        /*如果用户是null抛出异常*/
        /*如果成功返回用户信息*/
        User byUsername = userRepository.findByUsername(username);
        if (byUsername == null) {
            throw new UsernameNotFoundException("该用户尚未注册");
        }
        return byUsername;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
